﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SocketLib
{
	public class IPMPack
	{
		//[类型][编号][大小][数据]
		public int PackType { get; set; }
		public int PackNo { get; set; }
		public int PackSize { get; private set; }
		public byte[] Data { get; set; }


		/// <summary>
		/// 组包
		/// </summary>
		public byte[] Packed()
		{
			//using (MemoryStream ms = new MemoryStream())
			//{
			//    BinaryWriter writer = new BinaryWriter(ms);
			//    writer.Write(this.PackSize);
			//    writer.Write(this.PackSize);
			//    writer.Write(this.PackSize);
			//}
			
			this.PackSize = this.Data.Length + 12;

			byte[] bytea = BitConverter.GetBytes(this.PackSize);
			byte[] byteb = BitConverter.GetBytes(this.PackType);
			byte[] bytec = BitConverter.GetBytes(this.PackNo);
			byte[] byted = this.Data;

			byte[] byteDate = new byte[this.PackSize];
			Buffer.BlockCopy(bytea, 0, byteDate, 0, 4);
			Buffer.BlockCopy(byteb, 0, byteDate, 4, 4);
			Buffer.BlockCopy(bytec, 0, byteDate, 8, 4);
			Buffer.BlockCopy(byted, 0, byteDate, 12, this.Data.Length);
			return byteDate;
			

		}


		/// <summary>
		/// 解包
		/// </summary>
		public void UnPacked(byte[] ByteDate)
		{

			this.PackSize = BitConverter.ToInt32(ByteDate, 0);
			this.PackType = BitConverter.ToInt32(ByteDate, 4);
			this.PackNo = BitConverter.ToInt32(ByteDate, 8);
			byte[] byteDate = new byte[this.PackSize - 12];
			Buffer.BlockCopy(ByteDate, 12, byteDate, 0, this.PackSize - 12);

			this.Data = byteDate;

		}



		#region  固定协议
		/// <summary>
		/// 系统通信数据，NetService服务通信类型包都属于系统数据
		/// </summary>
		public const int Extends_System = 0;
		/// <summary>
		/// 文本消息数据，传输消息或者由用户指定要发送的信息，该类信息数据量小，切以文本形式居多
		/// </summary>
		public const int Extends_Message = 1;
		/// <summary>
		/// 指令数据，传输的通常是指定，指令包含系统(NetService)指令，或是用户应用程序自定义的指令，
		/// </summary>
		public const int Extends_Command = 2;
		/// <summary>
		/// 字节数据，传输的是用户自定义字符类数据
		/// </summary>
		public const int Extends_Byte = 3;

		#endregion
	}


}
